﻿using System;
using System.Diagnostics;
using System.Net;

namespace Red.Core.Network.PacketNetwork
{
    internal class PacketListener : IRawListenerInterface
    {
        public int AssignedRawListenerID = -1;
        public int AssignedID;
        private PacketConnetionCollection _connectionKeeper;
        private IDAllocator _idAllocator;
        private IPacketConnectionListener _callbackForNewConnections;

        public ulong TotalBytesReceived
        {
            get
            {
                return _connectionKeeper.GetTotalBytesReceivedForListener( AssignedID );
            }
        }

        public PacketListener( int id, PacketConnetionCollection connectionKeeper, IDAllocator idAllocator, IPacketConnectionListener callbackForNewConnections )
        {
            AssignedID = id;
            _connectionKeeper = connectionKeeper;
            _idAllocator = idAllocator;
            _callbackForNewConnections = callbackForNewConnections;
        }

        public void OnClosed(int listenerID)
        {

        }

        public bool OnConnection(int connectionID, out IRawConnectionInterface outConnectionInterface)
        {
            int packetConnectionID = _idAllocator.AllocateID();
            PacketConnection connection = new PacketConnection( packetConnectionID, AssignedID, _callbackForNewConnections );
            connection.RawConnectionID = connectionID;

            outConnectionInterface = connection;
            _connectionKeeper.AddConnection(packetConnectionID, connection);

            Debug.WriteLine("[PacketNetwork] New incoming connection accepted");

            return true;
        }
    }
}
